<template>
  <div class='container'>
    <el-card class="box-card">
  <div slot="header" >
    试题录入
  </div>

  <!-- 试题录入body内容，form表单包裹整个页面 -->
    <el-form :model="form" :rules="rules" ref="form"  label-width="7.5rem" class="demo-ruleForm">
      <!-- 下拉菜单内容 -->
      <el-form-item label="学科：" prop="Subject">
        <!-- 这里父标签要写prop，下面v-model用于数据回写 -->
        <!-- @focus触发聚焦事件，获取下拉数据内容 -->
        <el-select v-model="form.Subject" style="width:25rem" placeholder="请选择" @focus="SubjectApi" @change="getSubjectSelects">
          <el-option v-for="(item, index) in form.SubjectList" :key="index" :value="item.value" :label="item.label" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录：" prop="directoryName">
        <el-select v-model="form.directoryName"  style="width:25rem" placeholder="请选择" @change="CatalogId">
          <el-option v-for="(item, index) in form.CatalogueList" :key="index" :value="item.value" :label="item.label" ></el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="企业：" prop="Companys">
    <el-select v-model="form.Companys" style="width:25rem" placeholder="请选择" @focus="CompanysApi" @change="companyId">
      <el-option v-for="(item, index) in form.CompanysList" :key="index" :value="item.id" :label="item.company"></el-option>
    </el-select>
      </el-form-item>
      <el-form-item label="城市：" prop="province">
        <el-select v-model="form.province" style="width:12.5rem" placeholder="请选择" @focus="ProvincesApi" @change="getProvincesSelects">
          <el-option v-for="item in form.ProvincesList" :key="item.id" :value="item" ></el-option>
        </el-select>
        <el-select v-model="form.city" style="width:12.5rem" placeholder="请选择">
          <el-option v-for="item in form.CitysList" :key="item.id" :value="item" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向："  prop="direction">
    <el-select v-model="form.direction" style="width:25rem" placeholder="请选择" @focus="DirectionApi">
      <el-option v-for="item in form.DirectionList" :key="item.id" :value="item" ></el-option>
    </el-select>
      </el-form-item>
      <!-- 单选题型：题型、难度 -->
      <el-form-item label="题型：" prop="resourceQuestionType">
    <el-radio-group v-model="form.resourceQuestionType" size="medium" @change="questionTypeID">
      <el-radio label="1">单选</el-radio>
      <el-radio label="2">多选</el-radio>
      <el-radio label="3">简答</el-radio>
    </el-radio-group>
      </el-form-item>
      <el-form-item label="难度：" prop="resourceDifficulty">
    <el-radio-group v-model="form.resourceDifficulty" size="medium" @change="difficultyID">
      <el-radio label="1">简单</el-radio>
      <el-radio label="2">一般</el-radio>
      <el-radio label="3">困难</el-radio>
    </el-radio-group>
      </el-form-item>
      <!-- 富文本编辑器：题干 -->
      <el-form-item label="题干：" style="height: 18.75rem;" prop="question">
        <quill-editor ref="text" v-model="form.question" class="editor" :options="editorOption" style="height: 12.5rem;"></quill-editor>
      </el-form-item>

      <!-- 选项：试卷题目模板 -->
      <el-form-item label="选项：" for="options"  v-if="form.questionType === '1' || form.questionType === '2'">
         <!-- 竖着的:A\B\C\D -->
        <div class="option_item" v-for="(item, index) in form.options" :key="index">
          <!-- 单选时触发 -->
          <el-radio-group size="medium" v-model="form.options.code"  v-if="form.questionType === '1'" >
            <!-- 选择按钮 -->
            <el-radio :label="item.code" style="margin-right:0rem;">{{item.code}}：</el-radio>
            <!-- 输入框 -->
            <el-input v-model="item.title" placeholder="请输入内容" style="width:15rem"></el-input>
            <!-- 头像文件上传 -->
            <el-upload
              style="margin-left:.25rem;"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :file-list="item"
              >
              <img v-if="item.img" :src="item.img" class="avatar">

              <span style="font-size:.875rem" v-else>上传图片</span>
            </el-upload>
          </el-radio-group>
          <!-- 多选时触发 -->
          <el-checkbox-group v-model="checkList" v-else>
          <!-- 选择按钮 -->
          <el-checkbox :label="item.code">{{item.code}}：</el-checkbox>
          <!-- 输入框 -->
          <el-input v-model="item.title" placeholder="请输入内容" style="width:15rem"></el-input>
          <!-- 头像文件上传 -->
          <el-upload
              style="margin-left:.25rem;"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              >
              <img v-if="item.img" :src="item.img" class="avatar">
              <span style="font-size:.875rem" v-else>上传图片</span>
          </el-upload>
          </el-checkbox-group>
        </div>
      <!-- +增加选项与答案 -->
      <el-row>
        <el-button type="danger" :disabled="form.resourceQuestionType === '1' || AddOptionsAndAnswers==='1'" @click="AddOptions">+增加选项与答案</el-button>
      </el-row>
      </el-form-item>

      <!-- 解析视频 -->
      <el-form-item label="解析视频：" prop="videoURL">
        <el-input v-model="form.videoURL" style="width: 25rem;"></el-input>
      </el-form-item>
      <!-- 富文本编辑器：答案解析 -->
      <el-form-item label="答案解析：" style="height: 18.75rem;" prop="answer">
        <quill-editor ref="text" v-model="form.answer" class="editor" :options="editorOption" style="height: 12.5rem;"></quill-editor>
      </el-form-item>
      <!-- 题目备注 -->
      <el-form-item label="题目备注：" prop="remarks">
        <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="form.remarks"
            style="width: 25rem;">
        </el-input>
      </el-form-item>
      <!-- 试题标签： -->
      <el-form-item label="试题标签：" prop="tags">
        <el-select v-model="form.tags" multiple filterable allow-create default-first-option placeholder="请选择文章标签">
          <el-option v-for="item in form.TestQuestionLabelList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 确认提交 -->
      <el-form-item label="">
        <el-button type="primary" @click="button('form')">确认提交-测试专用</el-button>
        <!-- 别的组件页面，修改时跳转过来，显示成功，不显示提交 -->
        <el-button type="success" @click="WriteBack">修改按钮-暂时不用</el-button>
      </el-form-item>
    </el-form>
</el-card>
  </div>

</template>

<script>
import { SubjectList, CompanysList, Subjectcatalogue, SubjectTestQuestionLabel, FormSubmission, WriteBack } from '@/api/hmmm/questions.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction } from '@/api/hmmm/constants.js'
export default {
  name: 'QuestionsNew',
  data () {
    return {
      checkList: ['选中且禁用', ''],
      // v-model的form表单
      form: {
        type: [],
        resourceQuestionType: '',
        resourceDifficulty: '',
        options: [
          { isRight: false, code: 'A', title: '', img: null },
          { isRight: false, code: 'B', title: '', img: null },
          { isRight: false, code: 'C', title: '', img: null },
          { isRight: false, code: 'D', title: '', img: null }
        ],
        resourceOption: '',
        // 富文本编辑器:答案解析的v-model
        answer: '',
        // 学科下的目录里的 ID 值
        catalogID: null,
        // 省城市下的城市里面的值 与v-model绑定
        city: '',
        // 难度，简单，一般，困难 123
        difficulty: '',
        // 方向里面的值 与v-model绑定
        direction: '',
        // 企业 v-model的ID  在获取
        enterpriseID: null,
        // 省城市里面的值 与v-model绑定
        province: '',
        // 富文本编辑器:题干的v-model
        question: '',
        // 题型，单选，多选，简答 123
        questionType: '',
        // 题目备注
        remarks: '',
        // 学科自己的 ID zhi
        subjectID: null,
        // 试题标签里面的值，与v-model绑定
        tags: '',
        // 解析视频里面的值，与v-model绑定
        videoURL: '',
        // 企业里面的值 与v-model绑定
        Companys: '',
        // 目录里面的值 与v-model绑定
        directoryName: '',
        // 学科里面的值 与v-model绑定
        Subject: '',
        // 学科数组数据
        SubjectList: [],
        // 目录数组数据
        CatalogueList: [],
        // 企业数组数据
        CompanysList: [],
        // 省城市数组数据
        ProvincesList: [],
        // 省城市下的小城市数组数据
        CitysList: [],
        // 方向数组数据
        DirectionList: [],
        // 试题标签数组数据
        TestQuestionLabelList: [],
        name: ''
      },

      editorOption: {},

      // 选项 A B C D
      input: '',

      // 控制增加选项与答案的按钮
      AddOptionsAndAnswers: '2',
      radio: true,

      // 校验
      rules: {
        Subject: [{ required: true, message: '不能为空', trigger: 'blur' }],
        directoryName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        Companys: [{ required: true, message: '不能为空', trigger: 'blur' }],
        province: [{ required: true, message: '不能为空', trigger: 'blur' }],
        direction: [{ required: true, message: '不能为空', trigger: 'blur' }],
        resourceQuestionType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        resourceDifficulty: [{ required: true, message: '不能为空', trigger: 'blur' }],
        question: [{ required: true, message: '不能为空', trigger: 'blur' }],
        videoURL: [{ required: true, message: '不能为空', trigger: 'blur' }],
        answer: [{ required: true, message: '不能为空', trigger: 'blur' }],
        remarks: [{ required: true, message: '不能为空', trigger: 'blur' }],
        tags: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
  },
  mounted () {},
  components: {},
  props: {},
  computed: {},
  watch: {},
  methods: {
    handleAvatarSuccess (res, file) {
      this.form.options.forEach(item => {
        console.log(file.raw)
        item.img = URL.createObjectURL(file.raw)
        console.log(item.img)
      })
      console.log(this.form)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 学科 聚焦 获取数据
    async SubjectApi () {
      const { data } = await SubjectList()
      this.form.SubjectList = data
    },
    // 企业 聚焦 获取数据
    async CompanysApi () {
      const { data } = await CompanysList()
      this.form.CompanysList = data.items
    },
    // 省城市 聚焦 获取数据
    ProvincesApi () {
      this.form.ProvincesList = provinces()
    },
    // 方向 聚焦 获取数据
    DirectionApi () {
      this.form.DirectionList = direction
    },
    // 获取 学科 具体ID 发送请求
    async getSubjectSelects (val) {
      this.form.subjectID = val
      const catalogue = await Subjectcatalogue(val)
      const TestQuestionLabel = await SubjectTestQuestionLabel(val)
      this.form.TestQuestionLabelList = TestQuestionLabel.data
      this.form.CatalogueList = catalogue.data
    },
    // 获取 省城市 具体ID 发送请求
    getProvincesSelects (val) {
      this.form.CitysList = citys(val)
    },

    // 获取  企业 具体ID 赋值给提交表单的enterpriseId里
    companyId (val) {
      this.form.enterpriseID = val
    },
    // 获取 难度 简单、一般、困难123
    difficultyID (val) {
      this.form.difficulty = val
    },
    // 获取 题型  多选、单选、简答123
    questionTypeID (val) {
      this.form.questionType = val
    },
    CatalogId (val) {
      this.form.catalogID = val
    },
    // 点击增加选项与答案
    AddOptions () {
      this.form.options.push({ isRight: true, code: 'E', title: '', img: null })
      this.AddOptionsAndAnswers = '1'
    },
    // 测试数据专用按钮
    async button (form) {
      // // 手动校验
      // await this.$refs.form.validate()
      await this.$refs[form].validate((valid) => {
        if (valid) {
          alert('提交成功!')
        } else {
          console.log('提交失败')
          return false
        }
      })
      this.form.tags = []
      this.form.tags = this.form.tags.join(',')
      await FormSubmission(this.form)
      this.$refs[form].resetFields()
    },

    async WriteBack () {
      const { data } = await WriteBack()
      this.form = data
      const CompanysListData = await CompanysList()
      // 企业 根据ID 找数据回写
      CompanysListData.data.items.forEach(item => {
        if (item.id === data.enterpriseID) {
          const data = JSON.parse(JSON.stringify(item.company))
          this.form.Companys = data + ''
        }
      })
      this.Subject = data.subjectName
      const tagsArr = []
      tagsArr.push(data.tags)
      this.form.tags = tagsArr
    }

  }
}
</script>

<style>
.option_item {
    padding-bottom:1.25rem
  }
  .container {
    padding: 1.25rem;
  }

  .el-form-item__label:before {
    content:'*';
    color: #f56c6c;
    margin-right:.25rem;
  }

  .avatar-uploader {
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
  }
  .avatar-uploader .el-upload {
    border: .0625rem dashed #d9d9d9;
    border-radius: .375rem;
    cursor: pointer;
    position: relative;
    /* overflow: hidden; */
    width: 6.25rem;
    height: 3.75rem;
    line-height: 3.75rem;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .el-icon-circle-close {
    font-size: 1.125rem;
    color: #999;
    position:absolute;
    right:0;
    top: 0;
    transform: translate(50%,-50%);
    background: #fff;
  }
  .avatar {
    width: 6.25rem;
    height: 3.75rem;
    display: block;
    overflow: hidden;
  }

</style>
